package com.shuoyue.ycgk.base;


import android.content.Context;

import com.shuoyue.ycgk.net.exception.NetErrorException;
import com.shuoyue.ycgk.net.gsondefaultadapter.Optional;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author azheng
 * @date 2018/4/24.
 * GitHub：https://github.com/RookieExaminer
 * Email：wei.azheng@foxmail.com
 * Description：
 */
public class BasePresenter<V extends BaseView> {
    protected V mView;
    Context mContext;

    /**
     * 绑定view，一般在初始化中调用该方法
     *
     * @param view view
     */
    public void attachView(V view) {
        this.mView = view;
        this.mContext = mView.getCurrentContext();
    }

    /**
     * 解除绑定view，一般在onDestroy中调用
     */

    public void detachView() {
        this.mView = null;
    }

    /**
     * View是否绑定
     *
     * @return
     */
    public boolean isViewAttached() {
        return mView != null;
    }

    protected <T> ObservableSource<Optional<T>> apply(Observable<BaseResult<T>> observable) {
        return observable.compose(new RxTransformer().transfomateResult())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    public class RxTransformer {
        public <T> ObservableTransformer<BaseResult<T>, Optional<T>> transfomateResult() {
            return new ObservableTransformer<BaseResult<T>, Optional<T>>() {
                @Override
                public ObservableSource<Optional<T>> apply(Observable<BaseResult<T>> upstream) {
                    return upstream.flatMap((Function<BaseResult<T>, ObservableSource<Optional<T>>>) (BaseResult<T> result) -> {
                                if (result.getCode() == 0) {
                                    // 将返回结果进行包装
                                    return RxTransformer.this.createHttpData(result.transform());
                                } else {
                                    // 发送请求失败的信息
                                    return Observable.error(new NetErrorException(result.getMessage(), result.getCode()));
                                }
                                //                                     return Observable.empty();
                            }
                    );
                }
            };
        }

        public <T> Observable<Optional<T>> createHttpData(Optional<T> t) {

            return Observable.create(e -> {
                try {
                    e.onNext(t);
                    e.onComplete();
                } catch (Exception exc) {
                    e.onError(exc);
                }
            });
        }
    }

}
